package com.peng.my_blog.chat.converter;

import com.peng.my_blog.chat.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * All rights Reserved, Designed By www.rongdasoft.com
 *
 * @version V1.0
 * @Title: String2EnumConverter
 * @Description:
 * @author:wsp
 * @date: 2019/10/12
 * @Copyright: 2019/10/12 www.rongdasoft.com
 * Inc. All rights reserved.
 */
@Component
public class String2EnumConverter implements ConverterFactory<String, BaseEnum> {
    private static final Map<Class, Converter> converterMap = new HashMap<>();

    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        Converter<String, T> converter = converterMap.get(targetType);
        if (converter == null) {
            converter = new StringToEnum<>(targetType);
            converterMap.put(targetType, converter);
        }
        return converter;
    }

    private class StringToEnum<T extends BaseEnum> implements Converter<String, T> {
        private Map<Integer, T> enumMap = new HashMap<>();

        public StringToEnum(Class<T> enumType) {
            T[] enums = enumType.getEnumConstants();
            for (T e : enums) {
                enumMap.put(e.getCode(), e);
            }
        }

        public T convert(String source) {
            T t = enumMap.get(Integer.valueOf(source));
            if (t == null) {
                // 异常可以稍后去捕获
                throw new IllegalArgumentException("No element matches " + source);
            }
            return t;
        }
    }
}
